<template>
  <div
    class="contentIndex"
    :class="!scroll.isFixed ? 'noFixedTable' : 'fixedTable'"
    id="contentIndex"
  >
    <!-- 头部选择 -->
    <div class="create-index-look index-look">
      <a-select
        style="width: 182px"
        v-model:value="createSiteValue"
        placeholder="选择站点"
        @change="changeCreateSite"
        :options="siteOptions.map((item: dataSourceType) => ({ value: item.id, label: item.siteName }))"
      ></a-select>
      <a-tree-select
        style="width: 182px; margin-left: 8px"
        v-if="createSiteValue"
        placeholder="选择栏目"
        v-model:value="createColumnValue"
        ref="usermanage_treeSelect"
        show-search
        :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
        allow-clear
        treeNodeFilterProp="name"
        :fieldNames="{
          children: 'children',
          label: 'channelName',
          value: 'id',
        }"
        tree-default-expand-all
        :tree-data="siteData"
      >
      </a-tree-select>
      <a-button
        class="create-btn"
        :disabled="isNoCreateLook"
        style="margin-left: 8px"
        type="primary"
        @click="createIndex"
      >
        生成索引
      </a-button>
      <a-button
        :disabled="!btnPerm.includes('viewDetailAble')"
        class="look-btn"
        style="margin-left: 32px"
        type="primary"
        @click="toTaskList"
      >
        查看任务列表
      </a-button>
    </div>
    <div class="search-index-look index-look">
      <a-select
        style="width: 182px"
        v-model:value="searchSiteValue"
        placeholder="选择站点"
        @change="changeSearchSite"
        :options="siteOptions.map((item: dataSourceType) => ({ value: item.id, label: item.siteName }))"
      ></a-select>
      <a-tree-select
        style="width: 182px; margin-left: 8px"
        placeholder="筛选栏目"
        v-if="searchSiteValue"
        v-model:value="searchColumnValue"
        ref="usermanage_treeSelect"
        show-search
        :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
        allow-clear
        treeNodeFilterProp="name"
        :fieldNames="{
          children: 'children',
          label: 'channelName',
          value: 'id',
        }"
        tree-default-expand-all
        :tree-data="siteData"
        @change="changeSearchColumn"
      >
      </a-tree-select>

      <a-range-picker
        style="margin-left: 8px"
        :showTime="{ format: 'YYYY-MM-DD HH:mm' }"
        v-model:value="timeValue"
        :valueFormat="valueFormat"
        :disabledDate="disabledDate_after"
        :showNow="false"
        :disabledTime="disabledDateTime_after"
        @change="changeTime"
      />

      <a-input
        style="width: 182px; margin-left: 8px"
        v-model:value="datas.searchWord"
        placeholder="请输入标题名称"
        @blur="toSerachIndex"
        @pressEnter="toSerachIndex"
        class="titleSelect"
        allow-clear
      >
      </a-input>
      <a-button class="look-btn" style="margin-left: 8px" @click="toResetIndex">
        重置
      </a-button>
      <!-- <a-button
        class="look-btn"
        style="margin-left: 32px"
        type="primary"
        @click="toSerachIndex"
      >
        搜索
      </a-button> -->
    </div>
    <!-- 表格展示部分 -->
    <baseTable
      :columns="columns.contentIndexColumns"
      :dataSource="configData.records"
      :isSelect="true"
      :scroll="scroll"
      ref="contentIndexTables"
      :isShowPagination="isShowPagination"
      :showCheckDelete="showCheckDelete"
      :total="configData.total"
      @deleteRecord="deleteSelectedAll"
      @changePage="changePage"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a
            class="eidtRecords"
            :class="{ disable: !record.scanUrl || !btnPerm.includes('scanAble') }"
            @click="tobrowse(record)"
            >{{ record.oparation[0] }}</a
          >
          <a-popconfirm
            placement="topRight"
            :disabled="!btnPerm.includes('offlineAble')"
            @confirm="toOffline(record)"
          >
            <template #title>
              <p style="width: 197px">您确定下线此内容？</p>
            </template>
            <a
              class="eidtRecords"
              :class="{ disable: !btnPerm.includes('offlineAble') }"
              >{{ record.oparation[1] }}</a
            >
          </a-popconfirm>
          <a-popconfirm
            :disabled="!btnPerm.includes('deleteAble')"
            placement="topRight"
            ok-text="确定"
            cancel-text="取消"
            @confirm="confirmDelete(record)"
          >
            <template #title>
              <p style="width: 197px">您确定将该内容移入回收站？</p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">{{
              record.oparation[2]
            }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="offlineSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('offlineAble')"
          >下线</a-button
        >
        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')"
          >删除</a-button
        >
      </template>
    </baseTable>

    <!-- 创建索引模态框 -->
    <base-modal
      :width="modAlProps.width"
      :isVisible="isVisible"
      :title="modAlProps.title"
      :buttons="buttons"
      @handleOk="buttonMessage"
      @handleCancle="isVisible = false"
    >
      <template v-slot:body>
        <a-form
          name="advanced_search"
          autoComplete="off"
          class="ant-advanced-search-form"
          :model="formState"
          ref="contentIndexFrom"
        >
          <a-form-item
            :name="['indexName', 'value']"
            :label="formState.indexName.label"
            :rules="[formState.indexName.rule]"
          >
            <a-input
              v-model:value="formState.indexName.value"
              placeholder="不超过25个字"
              show-count
              :maxlength="25"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { useRouter } from "vue-router";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import { disabledDate_after, disabledDateTime_after } from "@/utils/common";
import { routerPerm } from "@/utils/common";
const btnPerm = ref<any[]>([]);
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
//data
const router = useRouter();
let scroll: scrollType = reactive({ y: "", isFixed: false });
const timeValue = ref<(string | number)[]>([]);
const checkedKeys = ref<(string | number | any)[]>([]);
const siteOptions = ref<dataSourceType[]>([]);
const valueFormat = ref("YYYY-MM-DD HH:mm:ss");
const createSiteValue = ref<String | undefined>(undefined);
const searchSiteValue = ref<String | undefined>(undefined);
const createColumnValue = ref<String | undefined>(undefined);
const searchColumnValue = ref<String | undefined>(undefined);
const siteData = ref<dataSourceType[]>([]);
const isShowPagination = true;
const showCheckDelete = true;
let datas = ref<dataSourceType>({});
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const contentIndexTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
const offlineArr = ref<(string | number)[]>([]);
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
const isVisible = ref<boolean>(false);
let isNoCreateLook = ref<boolean>(true);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "创建索引",
});
const contentIndexFrom = ref<any>("contentIndexFrom");
const formState = reactive<dataSourceType>({
  indexName: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "任务名称不可为空！",
      // validator: checkHotWord,
      // api: "fetchHotWordCategorysCateNameUnique",
      // params: { id: "" },
    },
    label: "任务名称",
  },
  id: "",
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改

// computed

isNoCreateLook = computed(() => {
  return !createSiteValue.value;
});

rowSelection = computed(() => {
  return contentIndexTables.value.selectedRowKeys;
});

//methods

// 选择生成的站点
const changeCreateSite = (e: any) => {
  fetchChannelListBySiteId(e);
};
// 选择查询的站点
const changeSearchSite = (e: any) => {
  datas.value.siteId = e;
  fetchChannelListBySiteId(e);
  getRdecord()
};

const fetchChannelListBySiteId = async (siteId: number) => {
  const postData = {
    siteId,
  };
  siteData.value = (await request.siteDocumentTree(postData)) as any;
};

// 时间选择
const changeTime = (data: any) => {
  datas.value.publishTimeStart = data ? data[0] + "" : "";
  datas.value.publishTimeEnd = data ? data[1] + "" : "";
  getRdecord()
};

//重置搜索条件
const toResetIndex = () => {
  datas.value.siteId = null;
  datas.value.channelId = null;
  datas.value.searchWord = "";
  searchSiteValue.value = undefined;
  searchColumnValue.value = undefined;
  datas.value.publishTimeStart = "";
  datas.value.publishTimeEnd = "";
  timeValue.value = [];
  getRdecord()
};

// 搜索内容索引
const toSerachIndex = () => {
  getRdecord();
};

// 选择生成的栏目
// const changeCreateColumn = (e) => {
//   console.log(createColumnValue.value, 11111);

// }
// 选择查询的栏目
const changeSearchColumn = (e: any) => {
  datas.value.channelId = e;
  getRdecord()
};

// 浏览
const tobrowse = (item: dataSourceType) => {
  if (item.scanUrl) {
    window.open(item.scanUrl);
  }
};
// 单个下线
const toOffline = (item: dataSourceType) => {
  // offlineArr.value = [item.id];
  offlineRecords([item.id]);
};

//批量下线
const offlineSelectedAll = () => {
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定下线选中的内容？",
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      okText: "确定",
      onOk: async () => {
        await offlineRecords(keys);
        Modal.destroyAll();
        contentIndexTables.value.selectedRowKeys = [];
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

// 删除单个内容
const confirmDelete = async (item: any) => {
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

//删除已选所有内容
const deleteSelectedAll = async () => {
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定将所选内容移入回收站？",
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
        contentIndexTables.value.selectedRowKeys = [];
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

// 调接口删除内容
const deleteRecords = async (keys: (string | number)[] = []) => {
  await request.fetchContentRecycle({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      getRdecord();
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};

// 调接口删除内容
const offlineRecords = async (ids: any[]) => {
  await request.fetchContentOffline({ ids }).then((res: any) => {
    if (res.code == "00000 00000") {
      getRdecord();
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};

// 获取内容索引表格数据
const getRdecord = async () => {
  const data: {} = {
    pageNumber: datas.value.pageNumber || pageCurrent.value,
    pageSize: datas.value.pageSize || pageSize.value,
    channelId: datas.value.channelId || "",
    siteId: datas.value.siteId || "",
    word: datas.value.searchWord || "",
    publishTimeStart: datas.value.publishTimeStart || "",
    publishTimeEnd: datas.value.publishTimeEnd || "",
  };
  const telData = (await request.fetchContentIndexPage(data)) || {};
  let reqData = telData;
  let contentIndexData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    contentIndexData = {
      channelId: item.channelId,
      oparation: ["浏览", "下线", "删除"],
      num: index + 1,
      siteId: item.siteId,
      indexTime: item.indexTime,
      publishTime: item.publishTime,
      siteName: item.siteName,
      title: item.title,
      channelName: item.channelName,
      id: item.id,
      ...item,
    };
    records.push(contentIndexData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  nextTick(() => {
    let obj = getTableScroll(112, "contentIndex", 38);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
    console.log(scroll, "scroll");
  });
};

// 新添或编辑内容调取接口
const buttonMessage = async (msg: dataSourceType) => {
  contentIndexFrom.value
    .validate()
    .then(() => {
      let params: dataSourceType = {
        channelId: createColumnValue.value,
        siteId: createSiteValue.value,
        taskName: formState.indexName.value,
      };
      request
        .fetchContentIndexTask(params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRdecord();
            formState.indexName.value = "";
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
      isVisible.value = false;
    })
    .catch(() => {});
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas.value.pageNumber = data.pageCurrent;
  datas.value.pageSize = data.pageSize;

  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  getRdecord();
};

//获取全部站点
const fetchContentAllSiteList = async () => {
  siteOptions.value = await request.fetchContentAllSiteList();
};

//创建索引
const createIndex = () => {
  isVisible.value = true;
  formState.indexName.value = "";
  buttons.value = [
    {
      text: "生成索引",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  nextTick(() => {
    contentIndexFrom.value.resetFields();
  });
};

//前往任务列表
const toTaskList = (record: any) => {
  router.push({
    path: "/config/contentIndex/viewTasks",
  });
};
//onmounted
onMounted(() => {
  btnPerm.value = routerPerm();
  getRdecord();
  fetchContentAllSiteList();
});
defineExpose({
  checkedKeys,
});
</script>
<style lang="less" scoped>
.contentIndex {
  width: 100%;
  height: calc(100% - 68px);
  padding: 16px;
  background-color: #fff;

  .index-look {
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .create-index-look {
    margin-top: 12px;
  }

  .search-index-look {
    margin-top: 24px;
    margin-bottom: 12px;
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

:deep(.ant-form-item) {
  width: 604px;
  display: flex;

  .ant-form-item-control {
    width: 494px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 94px;
    text-align: right;
  }
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

.noFixedTable {
  height: calc(100% - 72px);
}

.fixedTable {
  height: calc(100% - 120px);
}
</style>
